package io.mft.datasource.db.executor;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.mft.api.domain.DataAccessRegulation;
import io.mft.commons.function.ExecuteReturn;
import io.mft.commons.function.RequestValue;
import io.mft.datasource.db.accessor.DataAccessor;
import io.mft.datasource.db.accessor.bean.DAContext;
import io.mft.datasource.db.accessor.bean.DARequest;
import io.mft.datasource.db.accessor.bean.DbContextValue;


public abstract class DbTableSaveProcessExecutor extends DbProcessExecutor {
	Logger logger=LoggerFactory.getLogger(getClass());
	@Override
	protected ExecuteReturn invokeDbAccessor(DataAccessRegulation dataAccessRegulation,DAContext<DbContextValue> daRequestContext) {
		if (dataAccessRegulation.isMultipleParameterCommaSplit()) {
			DARequest request=daRequestContext.getRequest();
			Collection<DARequest> collection=buildMultipleDARequest(request);
			for (DARequest newRequest : collection) {
				DAContext<DbContextValue> context=new DAContext<DbContextValue>(daRequestContext.getContextValue(), newRequest, daRequestContext.getResponse());
				dataAccessor().doExecute(context);
			}
			ExecuteReturn executeReturn=ExecuteReturn.builder().build();
			return executeReturn;
		}else {
			ExecuteReturn daResponse = dataAccessor().doExecute(daRequestContext);
			return daResponse;
		}
	}
	private Collection<DARequest> buildMultipleDARequest(DARequest request) {
		Map<String, DARequest> newDARequestMap=new HashMap<>();
		Set<String> keys=request.getRequestValue().keySet();
		for (String key : keys) {
			String[] array=request.getRequestValue().getStr(key).split(",");
			String newKey=key.substring(0, key.length()-1);
			for (int i = 0; i < array.length; i++) {
				DARequest newDaRequest=newDARequestMap.get(String.valueOf(i));
				if (newDaRequest==null) {
					RequestValue requestValue=new RequestValue();
					newDaRequest=new DARequest(requestValue);
					newDARequestMap.put(String.valueOf(i), newDaRequest);
				}
				newDaRequest.getRequestValue().set(newKey, array[i]);
			}
		}
		Collection<DARequest> collection=newDARequestMap.values();	
		return collection;
	}
	protected abstract DataAccessor<DbContextValue> dataAccessor() ;
	public static void main(String[] args) {
		String newKey="ids".substring(0, "ids".length()-1);
		System.out.println(newKey);
	}
}
